package com.authsphere.security.account.redis.bind;

import com.authsphere.common.utils.JsonUtils;
import com.authsphere.security.account.api.bind.AccountBindTempTokenRepository;
import com.authsphere.security.account.api.bind.TempBindToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/20 22:11
 **/
public class RedisAccountBindTempTokenRepository implements AccountBindTempTokenRepository {

    private final RedisTemplate<String, String> redisTemplate;

    public RedisAccountBindTempTokenRepository(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void createNewToken(TempBindToken token) {
        String tokenJson = JsonUtils.toJsonString(token);
        String key = buildKey(token.getTokenValue());
        assert tokenJson != null;
        redisTemplate.opsForValue()
                .set(key, tokenJson, token.getExpireTime(), token.getTimeUnit());
    }

    @Override
    public TempBindToken getTokenForValue(String tokenValue) {
        String key = buildKey(tokenValue);
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return JsonUtils.parse(value, TempBindToken.class);
    }

    @Override
    public void removeToken(String tokenValue) {
        redisTemplate.delete(buildKey(tokenValue));
    }

    private String buildKey(String key) {
        return key;
    }
}
